<?php

namespace App\Managers\Admin\AdminUser;

use App\Exceptions\AdminException;
use App\Managers\BaseManager;
use App\Models\Admin\AdminUserModel;
use App\Models\AdminUsers;
use App\Util\LoginUtil;
use Illuminate\Support\Facades\Hash;


class AdminUserManager extends BaseManager
{
    public function __construct(AdminUserModel $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    public function _format($data)
    {
        foreach ($data as $item) {
            data_set($item, 'password', '');
            data_set($item, 'salt', '');
        }

        return $data;
    }

    public function _before_save()
    {
        if (isset($this->data['password']) && !empty($this->data['password']) && !empty($this->data['password_confirm'])) {
            if ($this->data['password'] !== $this->data['password_confirm']) {
                throw new AdminException('密码不一致');
            }
            unset($this->data['password_confirm']);
            //密码加密
            if (!empty($this->data['password'])) {
                $this->data['salt'] = Hash::make(md5($this->data['password']));
                $salt = $this->data['salt'] . config("app.salt");
                $this->data['password'] = md5(sha1(md5($this->data['password']) . $salt));
            }
        } else {
            unset($this->data['password']);
        }


        $id = $this->getData('id','');
        $password = $this->getData('password','');
        if (empty($id) && empty($password)) {
            throw new AdminException('新增用户请输入密码');
        }
        $account = data_get($this->data, 'account','');
        $phone = data_get($this->data, 'phone','');
        if (!empty($phone)){
            $phone_info =  AdminUserModel::query()->where('phone',$phone)->first();
            if (!empty($id)) $phone_info =  AdminUserModel::query()->where('id','!=',$id)->where(['phone'=>$phone,'guards'=>'admin'])->first();
            if (!empty($phone_info)) throw new AdminException('手机号码已被占用');
        }
        if ($account) {
            $admin_id = AdminUsers::query()->where('account', $account)->value('id');
            if ($admin_id && $id <> $admin_id) {
                throw new AdminException('该登录账号已被其他人使用');
            }
        }
    }
}
